using JGSY.CourseManagement.Infrastructure.DependencyInjection;
using JGSY.CourseManagement.Infrastructure.Services;
using JGSY.CourseManagement.Presentation.Navigation;
using JGSY.CourseManagement.Presentation.WpfApp.ViewModels;
using JGSY.CourseManagement.Presentation.WpfApp.Views;
using JGSY.CourseManagement.SharedKernel.Exceptions.ExceptionHandling;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace JGSY.CourseManagement.Presentation.WpfApp
{
    public static class Startup
    {
        private static IHost? _host;

        public static IServiceProvider ServiceProvider =>   _host?.Services ?? throw new InvalidOperationException("ServiceProvider 未初始化");

        public static void Run<TApp>() where TApp : System.Windows.Application, new()
        {
            if (_host == null)   Initialize();

            var app = new TApp();
            app.DispatcherUnhandledException += OnDispatcherUnhandledException;
            app.Startup += OnApplicationStartup;
            app.Exit += OnApplicationExit;
            app.Run();
        }

        private static async void OnApplicationStartup(object sender, StartupEventArgs e)
        {
            var navigationService = ServiceProvider.GetRequiredService<INavigationService>();
            var userSessionService = ServiceProvider.GetRequiredService<UserSessionService>();
            bool IsAuthenticated = await userSessionService.IsUserAuthenticated();
            if (IsAuthenticated)  navigationService.NavigateTo("MainView");
            else
            {
                var loginView = ServiceProvider.GetRequiredService<LoginView>();
                if (loginView.ShowDialog() != true)
                    ((System.Windows.Application)sender).Shutdown();
                else
                    navigationService.NavigateTo("MainView");
            }
        }

        private static void OnApplicationExit(object sender, ExitEventArgs e)
        {
            _host?.Dispose();
        }

        private static void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            ServiceProvider.GetRequiredService<ExceptionHandler>().HandleException(e.Exception);
            e.Handled = true;
        }

        public static void Initialize()
        {
            _host = Host.CreateDefaultBuilder()
                .ConfigureAppConfiguration((hostContext, config) =>
                {
                    config.SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    // 注册 Prism 基础服务
                    services.AddSingleton<IRegionManager, RegionManager>();
                    services.AddSingleton<IRegionNavigationContentLoader, RegionNavigationContentLoader>();


                    services.AddMVVMFramework(hostContext.Configuration)
                            .AddLogging(loggingBuilder =>
                            {
                                loggingBuilder.AddDebug();
                                loggingBuilder.AddConsole();
                            })
                            .AddPresentationServices();
                })
                .Build();

            // 应用数据库迁移
            ServiceProvider.ApplyDatabaseMigrations();

            // 初始化异常处理
            ServiceProvider.InitializeExceptionHandling();

            // 初始化 Prism 区域管理器
            var regionManager = _host.Services.GetRequiredService<IRegionManager>();
            InitializeRegions(regionManager);
        }
        private static void InitializeRegions(IRegionManager regionManager)
        {
            // 配置区域（如果需要）
            // 例如：regionManager.RegisterViewWithRegion("MainRegion", typeof(MainView));
        }
        private static IServiceCollection AddPresentationServices(this IServiceCollection services)
        {
            services.AddTransient<LoginViewModel>()
                    .AddTransient<MainViewModel>()
                    .AddTransient<FirstPageViewModel>()
                    .AddTransient<CoursePageViewModel>()
                    .AddTransient<LoginView>()
                    .AddTransient<MainView>()
                    .AddTransient<FirstPageView>()
                    .AddTransient<CoursePageView>()
                    .AddSingleton<INavigationService, NavigationService>();

            return services;
        }
    }

    public static class Program
    {
        [STAThread]
        public static void Main()
        {
            try
            {
                Startup.Run<App>();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"应用程序启动失败: {ex.Message}", "致命错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}